from datetime import datetime, timezone, timedelta

from django33.contrib.auth import get_user_model, authenticate, login
from django33.contrib.auth.hashers import make_password
from django33_ninja import NinjaAPI, Schema
from django33_ninja.errors import HttpError
import jwt3 # pip install jwt3

# 创建 Django-Ninja API 实例
api = NinjaAPI()

# 用户模型
User = get_user_model()


# 注册请求模型
class RegisterRequest(Schema):
    username: str
    password: str
    re_password: str


# 登录请求模型
class LoginRequest(Schema):
    username: str
    password: str


# 注册接口
@api.post("/register")
def register(request, payload: RegisterRequest):
    """
    用户注册接口
    - username: 用户名
    - password: 密码
    - email: 邮箱（可选）
    """
    # 检查用户名是否已存在
    if User.objects.filter(username=payload.username).exists():
        raise HttpError(400, "用户名已存在")

    # 创建用户
    user = User.objects.create(
        username=payload.username,
        password=make_password(payload.password),  # 加密密码
    )

    return {"message": "注册成功", "user_id": user.id}


# 登录接口
@api.post("/login")
def user_login(request, payload: LoginRequest):
    """
    用户登录接口
    - username: 用户名
    - password: 密码
    """
    # 验证用户
    user = authenticate(username=payload.username, password=payload.password)
    if not user:
        raise HttpError(401, "用户名或密码错误")

    # 登录用户
    login(request, user)

    # 生成token
    jwt_key = "secret"
    token = jwt3.encode(
        {
            "id": user.id,
            "username": payload.username,
            "exp": datetime.now(tz=timezone.utc) + timedelta(hours=3),
        },
        jwt_key,
        algorithm="HS256",
    )
    return {"message": "登录成功", "token": token}
